package com.base.netlib.interceptor

import android.text.TextUtils
import okhttp3.Interceptor
import okhttp3.Request
import okhttp3.Response
import java.io.IOException
import java.util.*

/**
 * @author taq
 */
class HeaderInterceptor : Interceptor {
    var headerBlock: (() -> Map<String, String?>)? = null

    @Throws(IOException::class)
    override fun intercept(chain: Interceptor.Chain): Response {
        val request: Request = chain.request()
        val headerMap = getHeaderMap()
        val builder: Request.Builder = request.newBuilder()
        for ((key, value) in headerMap) {
            value?.let {
                builder.addHeader(key, it)
            }
        }
        return chain.proceed(builder.build())
    }

    /**
     * 获取Header map
     */
    private fun getHeaderMap(): MutableMap<String, String?> {
        val commonHeader: MutableMap<String, String?> = mutableMapOf()
        headerBlock?.apply {
            commonHeader.putAll(this.invoke())
        }
        return commonHeader
    }
}